package com.hanfeng.weibo.client;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/***
 * 微博Oauth授权页面
 * @author hanfeng
 * @data 2012-9-3 下午6:02:28
 */
public class WebViewActivity extends Activity{
	//声明WebView控件
	private WebView webView;
	//声明进度条控件
	private ProgressDialog progressDialog;
	
	private static final int CLOSE_DIALOG = 1;
	
	//加载授权地址
	private static final String URL = "http://www.google.com.hk";
	
	//定义Handler
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.what == CLOSE_DIALOG) {
				//关闭进度条
				progressDialog.dismiss();
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		init();
		load(URL, webView);
	}
	
	public void init()
	{
		if (progressDialog == null) {
			Log.i("WebViewActivity", "加载进度条");
			progressDialog = new ProgressDialog(this);
		}
		//进度框title
		progressDialog.setTitle("加载页面中...");
		
		//显示进度条
		progressDialog.show();
		
		webView = (WebView)this.findViewById(R.id.wv_oauth);
		//设置是否启用js脚本
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setScrollBarStyle(0);//滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上 
//		webView.addJavascriptInterface(new JavascriptInterface(), "Methods");
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				load(URL, webView);
				return super.shouldOverrideUrlLoading(view, url);
			}
		});
		
		//判断页面是否加载完毕
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) { //全部加载完毕
					handler.sendEmptyMessage(CLOSE_DIALOG);
					Log.i("WebViewActivity", "URL加载完毕，关闭进度框");
				}
				super.onProgressChanged(view, newProgress);
			}
		});		
	}
	
	/**
	 * 加载页面
	 * @param url
	 */
	public void load(final String url,final WebView webView){
		//如果url为null 不加载数据
		if (null == url||"".equals(url)) {
			Log.i("WebViewActivity", "URL为空");
			return;
		}
		//通过线程加载页面
		new Thread(){
			@Override
			public void run() {
				super.run();
				webView.loadUrl(url);
				Log.i("WebViewActivity", "加载URL");
			}
		}.start();
	}
}
